/*
  Copyright 2007 Anders Båtstrand

      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

 */

package org.dyndns.anderlin.jmplayer.client.utilities;

import com.twmacinta.util.MD5;
import org.apache.log4j.Logger;
import org.dyndns.anderlin.jmplayer.model.Album;
import org.dyndns.anderlin.jmplayer.model.Track;
import org.tritonus.share.sampled.file.TAudioFileFormat;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;
import java.util.Map;

public class FileParser {


    private static Logger log = Logger.getLogger(FileParser.class);

    public static Album getAlbum(File file) {
        if (file == null || !file.canRead()) {
            log.error("Could not read file: " + file);
            return null;
        }
        Album album = new Album();
        AudioFileFormat baseFileFormat = null;
        try {
            baseFileFormat = AudioSystem.getAudioFileFormat(file);
        } catch (UnsupportedAudioFileException e) {
            log.error("Unsupported file format.", e);
        } catch (IOException e) {
            log.error("Could not read file information.", e);
        }

        if (baseFileFormat instanceof TAudioFileFormat) {
            Map properties = ((TAudioFileFormat) baseFileFormat).properties();
            album.setTitle((String) properties.get("album"));
        }
        return album;
    }


    // This will try to get information from the file, and make a track with suggestions filled in
    public static Track getTrack(File file) {
        if (file == null || !file.canRead()) {
            log.error("Could not read file: " + file);
            return null;
        }
        Track track = new Track();

        // get md5 hash
        try {
            String hash = MD5.asHex(MD5.getHash(file));
            track.setHash(hash);
        } catch (IOException e) {
            log.error("Could not read hash. Returning null", e);
            return null;
        }

        // http://www.javazoom.net/mp3spi/documents.html

        //        Standard parameters :
        // - duration : [Long], duration in microseconds.
        // - title : [String], Title of the stream.
        // - author : [String], Name of the artist of the stream.
        // - album : [String], Name of the album of the stream.
        // - date : [String], The date (year) of the recording or release of the stream.
        // - copyright : [String], Copyright message of the stream.
        // - comment : [String], Comment of the stream.
        AudioFileFormat baseFileFormat = null;
        try {
            baseFileFormat = AudioSystem.getAudioFileFormat(file);
        } catch (UnsupportedAudioFileException e) {
            log.error("Unsupported file format.", e);
        } catch (IOException e) {
            log.error("Could not read file information.", e);
        }

        if (baseFileFormat instanceof TAudioFileFormat) {
            Map properties = ((TAudioFileFormat) baseFileFormat).properties();
            //String key = "author";
            //artist = (String) properties.get(key);
            //key = "title";
            //title = (String) properties.get(key);
            //key = "album";
            //album = (String) properties.get(key);

            // This is in microseconds:
            Long duration = (Long) properties.get("duration");
            track.setDuration(duration / 1000000);
            String trackNumber = (String) properties.get("mp3.id3tag.track");
            track.setTrackNumber(string2Track(trackNumber));
        }


        log.info("Returning track: " + track);

        return track;
    }

    private static int string2Track(String s) throws NumberFormatException {

        if (s == null) {
            throw new NumberFormatException();
        }

        try {
            return Integer.parseInt(s);
        } catch (NumberFormatException e) {
            // don't throw this, we have more things to try! :-)
        }

        try {
            // is it on the form <tracknumber>/<total tracks> ?
            if (s.indexOf("/") > 0) {
                String strippedString = s.substring(0, s.indexOf("/"));
                return Integer.parseInt(strippedString);
            } else {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            throw e;
        }
    }

}
